package com.lihui.queue;


/**
 * 功能描述
 * 双向链表实现队列
 * @author wileda
 * @date 2022/10/18  21:22
 */
public class MyQueue {
    public static class ListNode{
        int val;
        ListNode prev;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;
    public ListNode tail;
    public int size;

    public void offer(int e){
        ListNode node = new ListNode(e);
        if(head == null){
            head = node;
        }else {
            tail.next = node;
            node.prev = tail;
        }
        tail = node;
        size++;
    }

    public int poll(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        int headValue = head.val;
        head = head.next;
        if(head == null){
            tail = null;
        }else {
            head.prev.next = null;
            head.prev = null;
        }
        size--;
        return headValue;
    }

    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return head.val;
    }
    public int size(){
        return size;
    }

    private boolean isEmpty() {
        return size == 0;
    }
    public void display(){
        StringBuilder  sb = new StringBuilder();
        if (head == null){
            sb.append("[]");
        }
        ListNode current = head;
            sb.append("[");
            while(current != null){
                sb.append(current.val);
                if(current.next != null){
                    sb.append(",");
                }
                current = current.next;
            }
            sb.append("]");
        System.out.println(sb);
    }
}
